import Material from '../../sql/module/factory/material'
import Template from '../../sql/module/factory/template'
import TemplateType from '../../sql/module/factory/template_type'
import StoreItem from '../../sql/module/factory/storeitem'
import MaterialTemplate from '../../sql/module/_dictionaries/material_store'
import ImgTemplate from '../../sql/module/factory/img_template'
import ImgXY from '../../sql/module/factory/img_x_y'
import UserUser from '../../sql/module/_dictionaries/user_user'
import ProcureList from '../../sql/module/factory/procure_list'
import Transfer from '../../sql/module/factory/transfer'
import PrintEncrypt from '../../sql/module/factory/print_encrypt'
import User from '../../sql/module/user/user'
import auth from '../../middlewares/auth'
import { Success, Fail, NotFoundItem, Repeatedly, Forbbidend, NotFound, Forbbiden } from '../../code/http-exception'
import { InfoValidator, ListValidator, NoParames } from '../../validators/public'
import { TypeValidator } from '../../validators/material'
import { StoreValidator, SetImageValidator, GetImageValidator, GetImagesValidator } from '../../validators/store'
import MaterialType from '../../sql/module/factory/material_type'
import { Op } from 'sequelize'
import Role from '../../sql/module/user/role'
import { sequelize } from '../../sql/db'
import ProcureOrder from '../../sql/module/factory/procure_order'
import { PROCURESTATE } from "../../lib/enum";

const router: Api = new Map()

ImgTemplate.hasOne(ImgXY)
ImgXY.belongsTo(ImgTemplate)

Material.hasOne(ImgXY)
ImgXY.belongsTo(Material)

User.hasMany(StoreItem)
StoreItem.belongsTo(User)

User.hasMany(Transfer)
Transfer.belongsTo(User)

User.hasMany(ProcureList)
ProcureList.belongsTo(User)

ProcureOrder.hasMany(ProcureList, { onDelete: 'SET NULL' })
ProcureList.belongsTo(ProcureOrder, { onDelete: 'SET NULL' })

User.hasMany(ProcureList)
ProcureList.belongsTo(User, {
    as: 'From', foreignKey: 'from'
})

StoreItem.hasMany(Transfer)
Transfer.belongsTo(StoreItem)

User.hasMany(Template)
Template.belongsTo(User)

Template.hasMany(StoreItem)
StoreItem.belongsTo(Template)

StoreItem.hasOne(ProcureList)
ProcureList.belongsTo(StoreItem)

Template.hasOne(ProcureList)
ProcureList.belongsTo(Template)

TemplateType.hasMany(Template);
Template.belongsTo(TemplateType);

Template.hasMany(ImgTemplate)
ImgTemplate.belongsTo(Template)

Template.belongsToMany(Material, { through: MaterialTemplate })
Material.belongsToMany(Template, { through: MaterialTemplate })
//获取材料列表
router.set('/materials', [auth(['addTemplateItem', 'itemList', 'saleStore']), async (ctx, next) => {
    const UserId = ctx.auth.id
    const materials = await MaterialType.findAll({
        where: { '$Materials.UserId$': UserId },
        attributes: ['id', 'name'],
        include: { model: Material, attributes: ['id', 'name', 'UserId'] }
    })
    throw new Success(materials)
}])

//获取产品类型列表
router.set('/types', [auth('public'), async (ctx, next) => {
    const template = await TemplateType.findAll()
    throw new Success(template)
}])

//获取全部权限为user的用户
router.set('/user', [auth(['addList', 'addSaleList']), async (ctx, next) => {
    const UserId = ctx.auth.id
    const user = await UserUser.findAll({
        attributes: [[sequelize.col('User.nickname'), 'nickname'], [sequelize.col('User.id'), 'id']],
        where: { UserId },
        include: { model: User, attributes: [] }
    })
    throw new Success(user)
}])

//获取全部权限为main的用户
router.set('/main', [auth('inProcureList'), async (ctx, next) => {
    const user = await User.findAll({
        attributes: ['id', 'nickname'],
        where: { '$Roles.name$': 'main' },
        include: { model: Role, attributes: [], through: { attributes: [] } }
    })
    throw new Success(user)
}])

//获取产品类型列表
router.set('/typeList', [auth('templateType'), async (ctx, next) => {
    const { rows, count } = await TemplateType.findAndCountAll()
    throw new Success({ list: rows, total: count })
}])

//添加产品类型
router.set('/addType', [auth('templateType'), async (ctx, next) => {
    const v = await new TypeValidator().validate(ctx)
    await TemplateType.create({
        name: v.get('body.name')
    })
    throw new Success()
}])

//删除产品类型
router.set('/delteType', [auth('templateType'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const type = await TemplateType.findOne({
        where: {
            id: v.get('query.id')
        }, include: Template
    })
    if (!type) { throw new NotFound() }
    if (type.dataValues.Templates.length) throw new Fail('存在相关产品，不可删除')
    await type.destroy()
    throw new Success()
}])

//添加产品
router.set('/addItem', [auth('addItem'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const UserId = ctx.auth.id
    const id = v.get('query.id')
    const number = v.get('body.number') || 0
    const price = v.get('body.price')
    const tag = v.get('body.tag')
    const imgs = v.get('body.imgs')
    const template = await Template.findOne({ where: { id } })
    if (!template) { throw new NotFoundItem() }
    await template.update({ price, tag })
    const { name, price: P } = template.dataValues
    const stores = Array(number * 1).fill({
        name,
        TemplateId: id,
        UserId,
        price: price || P
    })
    if (imgs) {
        const count = await ImgTemplate.count({ where: { TemplateId: template.dataValues.id } })
        const new_imgs = imgs.slice(count, imgs.length)
        await ImgTemplate.bulkCreate(new_imgs.map((item: any) => ({ TemplateId: template.dataValues.id, url: item })))
    }
    const storeItems = await StoreItem.bulkCreate(stores)
    throw new Success(storeItems.map(item => item.dataValues.id))
}])

//添加产品添加模版
router.set('/addTemplate', [auth('addTemplateItem'), async (ctx, next) => {
    const v = await new StoreValidator().validate(ctx)
    const UserId = ctx.auth.id
    const imgs = v.get('body.imgs')
    const MaterialIds = v.get('body.MaterialIds')
    const number = v.get('body.number') || 0
    const name = v.get('body.name')
    const tag = v.get('body.tag')
    const price = v.get('body.price')
    const TemplateTypeId = v.get('body.TemplateTypeId')
    const template = await Template.create({
        name, price, TemplateTypeId, UserId, tag
    })
    if (imgs) {
        await ImgTemplate.bulkCreate(imgs.map((item: any) => ({ TemplateId: template.dataValues.id, url: item })))
    }
    if (MaterialIds) {
        await MaterialTemplate.bulkCreate(MaterialIds.map((item: any) => ({ TemplateId: template.dataValues.id, MaterialId: item })))
    }
    const stores = Array(number * 1).fill({
        name,
        TemplateId: template.dataValues.id,
        UserId,
        price
    })
    const storeItems = await StoreItem.bulkCreate(stores)
    throw new Success(storeItems.map(item => item.dataValues.id))
}])
//获取codes
router.set('/codes', [auth('addTemplateItem'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const ids = v.get('body.id')
    const codes = await PrintEncrypt.findAll({
        where: { StoreItemId: ids }
    })
    throw new Success(codes)
}])
//模版列表
router.set('/templateList', [auth('template'), async (ctx, next) => {
    const v = await new ListValidator().validate(ctx)
    const UserId = ctx.auth.id
    const limit = v.get('query.limit')
    const page_index = v.get('query.page_index')
    const name = v.get('body.name')
    const TemplateTypeId = v.get('body.TemplateTypeId')
    const where: any = { UserId }
    const typeWhere: any = {}
    name && (where.name = {
        [Op.substring]: name
    })
    TemplateTypeId && (typeWhere.id = TemplateTypeId)
    const rows = await Template.findAll({
        where,
        include: [{ model: TemplateType, where: typeWhere, attributes: ['name'] }, ImgTemplate],
        limit: limit * 1,
        offset: (page_index - 1) * limit,
        order: [['state', 'DESC'], ['id', 'DESC']]
    })
    const count = await Template.count({ where })
    throw new Success({ list: rows, total: count })
}])
//仓库列表
router.set('/storeList', [auth(['itemList', 'saleStore']), async (ctx, next) => {
    const v = await new ListValidator().validate(ctx)
    const UserId = ctx.auth.id
    const limit = v.get('query.limit')
    const page_index = v.get('query.page_index')
    const name = v.get('body.name')
    const TemplateTypeId = v.get('body.TemplateTypeId')
    const where: any = { UserId }
    const typewhere: any = {}
    name && (where.name = {
        [Op.substring]: name
    })
    TemplateTypeId && (typewhere.TemplateTypeId = TemplateTypeId)
    const { rows, count } = await StoreItem.findAndCountAll({
        where,
        include: [{
            model: Template, where: typewhere, include: [
                { model: TemplateType, attributes: ['name', 'id'] }, ImgTemplate
            ]
        }],
        limit: limit * 1,
        offset: (page_index - 1) * limit,
        distinct: true,
        order: [['id', 'DESC']]
    })
    throw new Success({ list: rows, total: count })
}])

//模版下全部仓库列表
router.set('/getStoresByTemplate', [auth('itemList'), async (ctx, next) => {
    const v = await new ListValidator().validate(ctx)
    const UserId = ctx.auth.id
    const limit = v.get('query.limit')
    const page_index = v.get('query.page_index')
    const TemplateId = v.get('body.TemplateId')
    const where = { TemplateId }
    const typewhere = { UserId }
    const { rows, count } = await StoreItem.findAndCountAll({
        where,
        include: [{
            //@ts-ignore
            model: Template, where: typewhere, include: ImgTemplate
        }, {
            model: User, attributes: ['nickname', 'fullUrl', 'avatar']
        }],
        limit: limit * 1,
        offset: (page_index - 1) * limit,
        distinct: true,
        order: [['id', 'DESC']]
    })
    throw new Success({ list: rows, total: count })
}])

//用户获取我的产品列表
router.set('/storeSelfList', [auth('userAddItem'), async (ctx, next) => {
    const UserId = ctx.auth.id
    const where = { UserId }
    const typewhere = {}
    const rows = await StoreItem.findAll({
        where,
        include: [{
            model: Template, where: typewhere, include: [
                { model: TemplateType, attributes: ['name', 'id'] }, ImgTemplate
            ]
        }],
        limit: 10
    })
    throw new Success({ list: rows })
}])

//产品详情
router.set('/storeInfo', [auth('public'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('query.id')
    const UserId = ctx.auth.id
    const storeItem = await StoreItem.findOne({
        where: { id },
        include: [{
            model: Template, include: [
                { model: TemplateType }, ImgTemplate, { model: Material, through: { attributes: [] } }
            ]
            //@ts-ignore
        }, { model: Transfer, where: { UserId }, attributes: ['createdAt'], include: { model: User, attributes: ['nickname'] } }]
    })
    if (!storeItem) { throw new NotFoundItem('产品不存在') }
    throw new Success(storeItem)
}])

//用户获取产品详情
router.set('/storeSelfInfo', [auth('public'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('query.id')
    const storeItem = await StoreItem.findOne({
        where: { id },
        include: [{
            model: Template, include: [
                { model: TemplateType }, ImgTemplate, { model: Material, through: { attributes: [] } }
            ]
            //@ts-ignore
        }, { model: Transfer, attributes: ['createdAt'], include: { model: User, attributes: ['nickname'] } }]
    })
    throw new Success(storeItem)
}])

//用户添加产品
router.set('/addStoreSelf', [auth('public'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('query.id')
    const code = v.get('query.code')
    const UserId = ctx.auth.id
    const encrypt = await PrintEncrypt.findOne({ where: { code, StoreItemId: id } })
    if (!encrypt) { throw new Forbbidend('密文错误') }
    const count = await StoreItem.count({ where: { UserId } })
    if (count > 10) { throw new Forbbidend('最多添加10件产品') }
    const procure = await ProcureList.findOne({ where: { StoreItemId: id } })
    const storeItem = await StoreItem.findOne({
        where: { id }
    })
    if (!storeItem) throw new NotFound('不存在该商品')
    if (storeItem.dataValues.UserId || procure) { throw new Repeatedly('商品已绑定，请先联系解绑') }
    await storeItem.update({
        UserId
    })
    throw new Success()
}])

//用户删除产品
router.set('/removeStoreSelf', [auth('userAddItem'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('query.id')
    const UserId = ctx.auth.id
    await StoreItem.update({ UserId: null }, { where: { id, UserId } })
    throw new Success()
}])

//删除产品
router.set('/delete', [auth('deleteItem'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const UserId = ctx.auth.id
    const id = v.get('query.id')
    const store = await StoreItem.findOne({
        where: { id, UserId }
    })
    if (!store) { throw new NotFound() }
    await store.destroy()
    throw new Success()
}])

//获取模版详情
router.set('/itemInfo', [auth('itemInfo'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const UserId = ctx.auth.id
    const id = v.get('query.id')
    const template = await Template.findOne({
        where: { id, UserId },
        include: [{ model: Material, through: { attributes: [] } }, ImgTemplate]
    })
    throw new Success(template)
}])

//修改模版状态
router.set('/changeState', [auth('changeTemplateState'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const UserId = ctx.auth.id
    const id = v.get('query.id')
    const template = await Template.findOne({
        where: { id, UserId }
    })
    if (!template) { throw new NotFound() }
    const state = !template.dataValues.state
    await template.update({
        state
    })
    throw new Success(state)
}])

//出货
router.set('/addList', [auth(['addList', 'addSaleList']), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const from = ctx.auth.id
    const UserId = v.get('query.id')
    const storeitemIds = v.get('body.storeitemIds')
    const store = await StoreItem.findAll({ where: { id: storeitemIds } })
    const user = await User.findOne({ attributes: ['nickname', 'phone'], where: { id: UserId } })
    if (!user) { throw new NotFound('出货目标不存在') }
    const { nickname, phone } = user.dataValues
    const datas = store.map(item => {
        item.update({ UserId: null })
        const { id, TemplateId } = item.dataValues
        return { StoreItemId: id, TemplateId, from, UserId, state: PROCURESTATE.UN_PAY, address: nickname, phone }
    })
    await ProcureList.bulkCreate(datas)
    throw new Success()
}])

//销售
router.set('/addList1', [auth(['addList', 'addSaleList']), async (ctx, next) => {
    const v = await new NoParames().validate(ctx)
    const UserId = ctx.auth.id
    const storeitemIds = v.get('body.storeitemIds')
    const [affectedCount] = await StoreItem.update({ UserId: null, isSaled: 1 }, { where: { id: storeitemIds, UserId } })
    if (!affectedCount) { throw new NotFound() }
    throw new Success()
}])

//出货单列表
router.set('/outProcureList', [auth('outProcureList'), async (ctx, next) => {
    const v = await new NoParames().validate(ctx)
    const from = ctx.auth.id
    const UserId = v.get('body.UserId')
    const orderId = v.get('body.orderId')
    const where: any = { from }
    UserId && (where.UserId = UserId)
    orderId && (where.ProcureOrderId = orderId)
    const { rows, count } = await ProcureList.findAndCountAll({
        where,
        include: [{ model: StoreItem, attributes: ['price', 'id'] }, { model: Template, include: [ImgTemplate, TemplateType] },
        { model: User, attributes: ['nickname', 'id', 'AreaId'] }],
        distinct: true,
        order: [['UserId', 'DESC']]
    })
    throw new Success({ list: rows, total: count })
}])

//商家获取运费订单
router.set('/procureOrder', [auth('outProcureList'), async (ctx, next) => {
    const v = await new NoParames().validate(ctx)
    const from = ctx.auth.id
    const UserId = v.get('body.UserId')
    const { rows, count } = await ProcureOrder.findAndCountAll({
        where: { from, UserId },
        distinct: true
    })
    throw new Success({ list: rows, total: count })
}])

//筛选去向
router.set('/outProcureUser', [auth('outProcureList'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const UserId = v.get('body.id')
    const user = await User.findOne({
        attributes: ['id'],
        where: { id: UserId, AreaId: null }
    })
    throw new Success(user)
}])

//进货单列表
router.set('/inProcureList', [auth('inProcureList'), async (ctx, next) => {
    const v = await new NoParames().validate(ctx)
    const UserId = ctx.auth.id
    const from = v.get('body.from')
    const where: any = { UserId }
    from && (where.from = from)
    const { rows, count } = await ProcureList.findAndCountAll({
        where,
        include: [{ model: Template, include: [ImgTemplate, TemplateType] }, { model: StoreItem, attributes: ['price'] },
        { model: User, as: 'From', attributes: ['nickname', 'id'] }],
        distinct: true
    })
    throw new Success({ list: rows, total: count })
}])

//确认收货
router.set('/confrim', [auth('inProcureList'), async (ctx, next) => {
    const v = await new NoParames().validate(ctx)
    const UserId = ctx.auth.id
    const storeItemIds = v.get('body.storeItemIds')
    const where = { UserId, id: storeItemIds }
    const procureList = await ProcureList.findAll({ where })
    await Promise.all(procureList.map(async item => {
        const { StoreItemId, state } = item.dataValues
        if (StoreItemId && state === PROCURESTATE.IN_TRANSIT) {
            const storeitem = await StoreItem.findOne({ where: { id: item.dataValues.StoreItemId } })
            await storeitem?.update({ UserId: item.dataValues.UserId })
            return item.destroy()
        } else {
            throw new Fail('订单未发货，请稍后重试')

        }
    }))
    throw new Success()
}])

//商家获取未确认订单
router.set('/unConfirmList', [auth('outProcureList'), async (ctx, next) => {
    const UserId = ctx.auth.id
    const { rows, count } = await ProcureList.findAndCountAll({
        where: { from: UserId, state: PROCURESTATE.UN_CONFIRM },
        include: [{ model: User, attributes: ['nickname', 'avatar', 'fullUrl'] }, { model: Template, attributes: ['name'] }],
        distinct: true,
        limit: 6
    })
    throw new Success({ list: rows, total: count })
}])

//预定订单填写商品Id
router.set('/setId', [auth('outProcureList'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const UserId = ctx.auth.id
    const id = v.get('query.id')
    let StoreItemId = v.get('body.StoreItemId')
    const where = { from: UserId, id }
    const procure = await ProcureList.findOne({ where })
    if (!procure) { throw new NotFoundItem('出货单未找到') }
    const TemplateId = procure.dataValues.TemplateId
    let storeitem = null
    if (StoreItemId) {
        storeitem = await StoreItem.findOne({ where: { id: StoreItemId, UserId } })
        if (!storeitem) { throw new NotFoundItem('未发现商品') }
        if (TemplateId !== storeitem.dataValues.TemplateId) { throw new Forbbidend('绑定商品模版Id于预定不符') }
    } else {
        storeitem = await StoreItem.findOne({ where: { TemplateId, UserId } })
        if (!storeitem) { throw new NotFoundItem('未发现符合商品') }
        StoreItemId = storeitem.dataValues.id
    }
    await storeitem?.update({ UserId: null })
    await procure.update({ StoreItemId })
    throw new Success(StoreItemId)
}])

//确认订单
router.set('/confirm', [auth('outProcureList'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const from = ctx.auth.id
    const ids = v.get('body.id')
    let orderId = v.get('body.orderId')
    const UserId = v.get('body.UserId')
    const address = v.get('body.address')
    const freight = v.get('body.freight') || 0
    let state = PROCURESTATE.UN_PAY
    const procureOrder = await ProcureOrder.findOrCreate({
        where: { id: orderId || null }, defaults: {
            from, UserId, address, freight
        }
    })
    orderId = procureOrder[0].dataValues.id
    if (procureOrder[0].dataValues.state) state = PROCURESTATE.HAS_PAY
    const where = { from, id: ids, state: [PROCURESTATE.UN_CONFIRM, PROCURESTATE.UN_PAY] }
    const res = await ProcureList.update({ state, ProcureOrderId: orderId }, { where })
    if (res[0] === 0) { throw new NotFoundItem('未发现订单或订单已支付') }
    throw new Success()
}])

//确认订单（商家）
router.set('/confirmUser', [auth('outProcureList'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const from = ctx.auth.id
    const ids = v.get('body.id')
    const where = { from, id: ids, state: PROCURESTATE.UN_CONFIRM }
    const res = await ProcureList.update({ state: PROCURESTATE.UN_PAY }, { where })
    if (res[0] === 0) throw new NotFoundItem('未发现订单或已确认')
    throw new Success()
}])

//删除运费订单
router.set('/deleteOrder', [auth('outProcureList'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const from = ctx.auth.id
    const orderId = v.get('query.id')
    const procure = await ProcureList.findAll({
        where: {
            from, ProcureOrderId: orderId
        }
    })
    if (procure.length !== 0) throw new Forbbidend('订单存在商品，不可删除')
    const procureOrder = await ProcureOrder.findOne({ where: { from, id: orderId } })
    if (!procureOrder) { throw new Forbbidend('订单不存在') }
    if (procureOrder?.dataValues.state) {
        // 退款
    }
    await procureOrder.destroy()
    throw new Success()
}])

//发货
router.set('/transet', [auth('outProcureList'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('query.id')
    const from = ctx.auth.id
    const where = { from, id, StoreItemId: { [Op.not]: null }, state: [PROCURESTATE.HAS_PAY, PROCURESTATE.UN_PAY] }
    const res = await ProcureList.update({ state: PROCURESTATE.IN_TRANSIT }, { where })
    if (res[0] === 0) { throw new NotFoundItem('订单未绑定商品') }
    throw new Success()
}])

//退回出货
router.set('/back', [auth('outProcureList'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('query.id')
    const item = await ProcureList.findOne({ where: { id, state: [PROCURESTATE.UN_CONFIRM, PROCURESTATE.UN_PAY] } })
    if (!item) { throw new NotFoundItem('当前状态，不可召回') }
    const { from, StoreItemId } = item.dataValues
    await StoreItem.update({ UserId: from }, { where: { id: StoreItemId } })
    await item.destroy()
    throw new Success()
}])

//获取产品图片
router.set('/images', [auth('updateImg'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('query.id')
    const UserId = ctx.auth.id
    const storeItem = await Template.findOne({
        where: { id, UserId },
        include: [ImgTemplate,
            { model: Material, through: { attributes: [] } }
        ]
    })
    throw new Success(storeItem)
}])
//设置产品图片
router.set('/setPoint', [auth('updateImg'), async (ctx, next) => {
    const v = await new SetImageValidator().validate(ctx)
    const ImgTemplateId = v.get('body.ImgTemplateId')
    const MaterialId = v.get('body.MaterialId')
    const offsetX = v.get('body.offsetX')
    const offsetY = v.get('body.offsetY')
    await ImgXY.create({
        ImgTemplateId, MaterialId, offsetX, offsetY
    })
    throw new Success()
}])
//获取一个材料在产品图片上的点（添加、删除点时使用）
router.set('/getPoint', [auth('updateImg'), async (ctx, next) => {
    const v = await new GetImageValidator().validate(ctx)
    const ImgTemplateId = v.get('body.ImgTemplateId')
    const MaterialId = v.get('body.MaterialId')
    const rows = await ImgXY.findAll({
        where: { ImgTemplateId, MaterialId },
        include: Material
    })
    throw new Success(rows)
}])
//获取所有材料在产品图片上的点
router.set('/getPoints', [auth('public'), async (ctx, next) => {
    const v = await new GetImagesValidator().validate(ctx)
    const ImgTemplateId = v.get('body.ImgTemplateId')
    const TemplateId = v.get('body.TemplateId')
    const template = await Template.findOne({
        attributes: [],
        where: { id: TemplateId },
        include: [{ model: Material, attributes: ['id'], through: { attributes: [] } }]
    })
    if (!template) { throw new NotFound('模版未发现') }
    const rows = await ImgXY.findAll({
        where: { ImgTemplateId, MaterialId: template.dataValues.Materials.map((item: { id: any }) => item.id) },
        include: Material
    })
    throw new Success(rows)
}])
//删除图片点
router.set('/deletePoint', [auth('updateImg'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('query.id')
    const imgPoint = await ImgXY.findOne({
        where: { id }
    })
    if (!imgPoint) { throw new NotFound() }
    await imgPoint.destroy()
    throw new Success()
}])

//历史记录
router.set('/history', [auth('history'), async (ctx, next) => {
    const v = await new ListValidator().validate(ctx)
    const from = ctx.auth.id
    const limit = v.get('query.limit')
    const page_index = v.get('query.page_index')
    const nickname = v.get('body.nickname')
    const tag = v.get('body.tag')
    const name = v.get('body.name')
    const where: any = { from }
    const user_where: any = {}
    const store_where: any = {}
    nickname && (user_where.nickname = {
        [Op.substring]: nickname
    })
    tag && (where.tag = {
        [Op.substring]: tag
    })
    name && (store_where.name = {
        [Op.substring]: name
    })
    const { rows, count } = await Transfer.findAndCountAll({
        where,
        include: [{ model: StoreItem, where: store_where }, { model: User, where: user_where, attributes: ['nickname'] }],
        limit: limit * 1,
        offset: (page_index - 1) * limit,
        distinct: true,
        order: [['createdAt', 'DESC']]
    })
    throw new Success({ list: rows, total: count })
}])

//订单备注
router.set('/setTransTag', [auth('history'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('body.id')
    const tag = v.get('body.tag')
    await Transfer.update({ tag }, { where: { id } })
    throw new Success()
}])

export { router }